<?php

namespace App\Http\Controllers\Mini;

use App\Http\Controllers\Home\PaymentController;
use App\Models\Activitys;
use App\Models\Addresses;
use App\Models\AdminAgencys;
use App\Models\Areas;
use App\Models\Articles;
use App\Models\BalanceLogs;
use App\Models\BidLists;
use App\Models\BondReturnLogs;
use App\Models\Buys;
use App\Models\CashOuts;
use App\Models\Categorys;
use App\Models\Collections;
use App\Models\CompanyInfos;
use App\Models\Configs;
use App\Models\Demands;
use App\Models\Feedbacks;
use App\Models\Footprints;
use App\Models\Goods;
use App\Models\GoodsEvaluates;
use App\Models\IntegralLogs;
use App\Models\Mails;
use App\Models\OrderGoods;
use App\Models\Orders;
use App\Models\ProfitLogs;
use App\Models\Regions;
use App\Models\SignUps;
use App\Models\Stores;
use App\Models\UserInfos;
use App\Models\Users;
use App\Models\Wechat;
use App\Models\WordDownloadLogs;
use App\Models\Words;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class MyController extends Controller
{
    /**
     * 用户签到
     * @route api.user.userSignIn
     * @param user_id 用户id
     */
    public function userSignIn(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','sign_in_at','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($user_info['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($user_info['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($user_info['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $lists = [];
            $lists['is_sign'] = 0;//默认未签到
            if (trim(@date('Y-m-d', strtotime($user_info['sign_in_at']))) != trim(date('Y-m-d'))) {
                //签到送积分
                $integral = Configs::getConfig('integral');
                if($user_info['type'] == 1) {
                    $sign_in = $integral['hr_sign_in'];
                }else {
                    $sign_in = $integral['bus_login'];
                }
                Users::where('id',$user_id)->increment('integral',$sign_in);
                //添加日志记录
                $integral_arr = [
                    'user_id' => $user_id,
                    'user_name' => $user_info['username'],
                    'integral' => '+'.$sign_in,
                    'desc' => '签到送积分',
                    'type' => 1,
                ];
                IntegralLogs::create($integral_arr);
                $lists['integral'] = $sign_in;//签到赠送的积分
                $lists['is_sign'] = 1;//已签到
                Users::where('id',$user_id)->update(['sign_in_at' => date('Y-m-d H:i:s')]);

                return response()->json([
                    "code" => 1,
                    "msg" => "签到成功",
                    "data" => $lists
                ]);
            }else {
                return response()->json([
                    "code" => 1,
                    "msg" => "已签到",
                    "data" => $lists
                ]);
            }

        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 个人中心首页数据
     * @route api.user.userIndex
     * @param user_id 用户id
     */
    public function userIndex(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $fields = ['id','username','nickname','mobile','avatar','integral','balance','status','type','sign_in_at','integral_grade'];
            $user_info = Users::where('id',$user_id)->where('status','<>',-1)->first($fields);
            if (empty($user_info)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            if($user_info['status'] == 1){
                $user_info['massage'] = Mails::where(['user_id'=>$user_info['id'], 'status'=>1])->count();
                //判断当天是否签到
                $user_info['is_sign'] = 0;//默认未签到
                if (trim(@date('Y-m-d', strtotime($user_info['sign_in_at']))) == trim(date('Y-m-d'))) {
                    $user_info['is_sign'] = 1;//已签到
                }
                if($user_info['type'] == 1){
                    //订单量
                    $order_wait_pay = Orders::getCounts(['user_id'=>$user_info['id'],'order_state'=>2]);
                    $user_info['order_wait_pay'] = strlen($order_wait_pay)>=4 ? '999+' : $order_wait_pay;
                    $order_wait_send = Orders::getCounts(['user_id'=>$user_info['id'],'order_state'=>3]);
                    $user_info['order_wait_send'] = strlen($order_wait_send)>=4 ? '999+' : $order_wait_send;
                    $order_wait_take = Orders::getCounts(['user_id'=>$user_info['id'],'order_state'=>4]);
                    $user_info['order_wait_take'] = strlen($order_wait_take)>=4 ? '999+' : $order_wait_take;
                    $order_wait_evaluate = Orders::getCounts(['user_id'=>$user_info['id'],'order_state'=>5,'evaluation_state'=>1]);
                    $user_info['order_wait_evaluate'] = strlen($order_wait_evaluate)>=4 ? '999+' : $order_wait_evaluate;
                }elseif ($user_info['type'] == 2){
                    $user_info['store_id'] = Stores::where('user_id',$user_id)->value('id');
                    if($user_info['integral']>=100 && $user_info['integral']<1000){
                        $user_info['integral_grade'] = 1;
                    }elseif ($user_info['integral']>=1000 && $user_info['integral']<2000){
                        $user_info['integral_grade'] = 2;
                    }elseif ($user_info['integral']>=2000 && $user_info['integral']<3000){
                        $user_info['integral_grade'] = 3;
                    }elseif ($user_info['integral']>=3000 && $user_info['integral']<4000){
                        $user_info['integral_grade'] = 4;
                    }
                    Users::where('id',$user_id)->update(['integral_grade'=>$user_info['integral_grade']]);
                }
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $user_info
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户足迹列表
     * @route api.user.userFootprint
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     */
    public function userFootprint(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where('id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($user_info)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',5);//条数
            //分组获取信息
            $lists = Footprints::select(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date ,GROUP_CONCAT(id) as ids"))
                ->where('user_id',$user_id)
                ->groupBy(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))
                ->orderBy("date","desc")->paginate($limit, null, null, $page);
            foreach ($lists as $key=>$val){
                $ids = explode(",", $val['ids']);
                $lists[$key]['data'] = Footprints::apiLists(['id'=>$ids], ['id','user_id','foot_id','type']);
                unset($val['ids']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户基本信息
     * @route api.user.userInfo
     * @param user_id 用户id
     */
    public function userInfo(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $fields = ['id','avatar','username','nickname','sex','area','qq','mobile','email','type','wechat','bank_name','bank_sn'];
            $users = Users::where('id',$user_id)->where('status','<>',-1)->first($fields);
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
            $user_info = UserInfos::where('user_id',$user_id)->first();
            if (empty($user_info)) return response()->json(["code"=>0, "msg"=>'数据错误']);

            $users['area_name'] = Areas::where('id',$users['area'])->value('name');
            $users['company_name'] = $user_info['company_name'];
            //HR
            $users['hr_department'] = $user_info['hr_department'];
            $users['hr_position'] = $user_info['hr_position'];
            $users['company_type_id'] = CompanyInfos::where('id',$user_info['company_type'])->value('id');
            $users['company_type_name'] = CompanyInfos::where('id',$user_info['company_type'])->value('name');
            $users['company_industry_id'] = CompanyInfos::where('id',$user_info['company_industry'])->value('id');
            $users['company_industry_name'] = CompanyInfos::where('id',$user_info['company_industry'])->value('name');
            $users['company_size_id'] = CompanyInfos::where('id',$user_info['company_size'])->value('id');
            $users['company_size_name'] = CompanyInfos::where('id',$user_info['company_size'])->value('name');
            //供应商
            $users['master_name'] = $user_info['master_name'];
            $users['company_email'] = $user_info['company_email'];
            $users['license'] = $user_info['license'];
            $users['qualification'] = empty($user_info['qualification']) ? [] : $user_info['qualification'];
            $users['qrganization_code'] = $user_info['qrganization_code'];

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $users
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户基本信息修改
     * @route api.user.userInfoEdit
     * @param user_id 用户id
     * 共有的
     * @param sex 性别 1男 2女
     * @param qq QQ
     * @param company_name 公司名称
     * HR
     * @param avatar 头像
     * @param nickname 姓名
     * @param email 邮箱
     * @param company_type 公司类型
     * @param company_industry 公司行业
     * @param company_size 公司规模
     * @param link_department HR部门
     * @param link_position HR职位
     * 供应商
     * @param bank_name 开户行
     * @param bank_sn 银行账户
     * @param wechat 微信
     * @param area 区域(地区信息接口：home.public.area 不传参)
     * @param license 营业执照
     * @param qualification 资格证书
     * @param qrganization_code 营业执照组织机构代码
     * @param company_email 供应商公司邮箱
     * @param master_name 供应商负责人姓名
     */
    public function userInfoEdit(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::getUserInfo(['id'=>$user_id]);
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
            $user_info = UserInfos::Where('user_id',$user_id)->first();

            $users->sex = (int)$request->post('sex',1);
            $users->qq = (string)$request->post('qq');
            $user_info->company_name = (string)$request->post('company_name');
            if ($users['type'] == 1){
                $users->avatar = (string)$request->post('avatar');
                $users->username = (string)$request->post('nickname');
                $users->nickname = (string)$request->post('nickname');
                $users->email = (string)$request->post('email');
                $user_info->company_type = (int)$request->post('company_type');
                $user_info->company_size = (int)$request->post('company_size');
                $user_info->company_industry = (int)$request->post('company_industry');
                $user_info->hr_department = (string)$request->post('hr_department');
                $user_info->hr_position = (string)$request->post('hr_position');
            }elseif ($users['type'] == 2){
                $users->username = (string)$request->post('company_name');
                $users->bank_name = (string)$request->post('bank_name');
                $users->bank_sn = (string)$request->post('bank_sn');
                $users->wechat = (string)$request->post('wechat');
                $users->area = (int)$request->post('area');
                $user_info->company_email = (string)$request->post('company_email');
                $user_info->master_name = (string)$request->post('master_name');
                $user_info->license = (string)$request->post('license');
                $user_info->qualification = $request->post('qualification');
                $user_info->qrganization_code = (string)$request->post('qrganization_code');
            }

            $users->save();
            $user_info->save();

            return response()->json([
                "code" => 1,
                "msg" => "操作成功",
                "data" => $users
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户资产信息
     * @route api.user.userAsset
     * @param user_id 用户id
     */
    public function userAsset(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $fields = ['id','username','integral','balance','bond','profit','contract','cash','member_fee','member_fee_at'];
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first($fields);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $users
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户积分记录列表
     * @route api.user.userIntegralLogs
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     */
    public function userIntegralLogs(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);

            $lists = IntegralLogs::select(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date ,GROUP_CONCAT(id) as ids"))
                ->where('user_id',$user_id)
                ->groupBy(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))
                ->orderBy("date","desc")->paginate($limit, null, null, $page);
            foreach ($lists as $key=>$val){
                $ids = explode(",", $val['ids']);
                $lists[$key]['list'] = IntegralLogs::allLists(['id'=>$ids], ['id','user_id','desc','integral','type']);
                unset($val['ids']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户余额记录列表
     * @route api.user.userBalanceLogs
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     */
    public function userBalanceLogs(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);

            $lists = BalanceLogs::select(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date ,GROUP_CONCAT(id) as ids"))
                ->where('user_id',$user_id)->where('pay_state',2)
                ->groupBy(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))
                ->orderBy("date","desc")->paginate($limit, null, null, $page);

            foreach ($lists as $key=>$val){
                $ids = explode(",", $val['ids']);
                $lists[$key]['list'] = BalanceLogs::allLists(['id'=>$ids], ['id','user_id','desc','balance','type']);
                unset($val['ids']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户获取积分提示
     * @route api.user.userGetIntegral
     * @param user_id 用户id
     */
    public function userGetIntegral(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['id','username','integral','sign_in_at','login_at','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $base = Configs::getConfig('integral');
            $act = SignUps::where('user_id',$user_id)->orderBy('pay_at', 'desc')->value('pay_at');
            $goods = Orders::where('user_id',$user_id)->orderBy('pay_time', 'desc')->value('pay_time');
            $demand = Demands::where('user_id',$user_id)->orderBy('created_at', 'desc')->value('created_at');
            $recharge = BalanceLogs::where(['user_id'=>$user_id,'type'=>1])->orderBy('created_at', 'desc')->value('created_at');
            $profit = ProfitLogs::where('user_id',$user_id)->orderBy('created_at', 'desc')->value('created_at');
            $lists = [];
            if ($user_info['type'] == 1){
                $lists['register'] = $base['hr_register'];
                $lists['login'] = $base['hr_login'];
                $lists['sign_in'] = $base['hr_sign_in'];
                $lists['call'] = $base['hr_call'];
                $lists['activity'] = $base['hr_activity'];
                $lists['goods'] = $base['hr_goods'];
                $lists['demand'] = $base['hr_demand'];
                $lists['register_state'] = 1;
                $lists['login_state'] = 0;
                $lists['sign_in_state'] = 0;
                $lists['call_state'] = 0;
                $lists['activity_state'] = 0;
                $lists['goods_state'] = 0;
                $lists['demand_state'] = 0;
                if (trim(@date('Y-m-d', strtotime($user_info['login_at']))) == trim(date('Y-m-d'))){
                    $lists['login_state'] = 1;
                }
                if (trim(@date('Y-m-d', strtotime($user_info['sign_in_at']))) == trim(date('Y-m-d'))){
                    $lists['sign_in_state'] = 1;
                }
                if (trim(@date('Y-m-d', strtotime($act))) == trim(date('Y-m-d'))){
                    $lists['activity_state'] = 1;
                }
                if (trim(@date('Y-m-d', strtotime($goods))) == trim(date('Y-m-d'))){
                    $lists['goods_state'] = 1;
                }
                if (trim(@date('Y-m-d', strtotime($demand))) == trim(date('Y-m-d'))){
                    $lists['demand_state'] = 1;
                }
            }elseif ($user_info['type'] == 2){
                if($user_info['integral'] <= 1000){
                    $lists['register_grade'] = 1;
                }elseif ($user_info['integral'] > 1000 && $user_info['integral'] <= 2000){
                    $lists['register_grade'] = 2;
                }elseif ($user_info['integral'] > 2000 && $user_info['integral'] <= 3000){
                    $lists['register_grade'] = 3;
                }elseif ($user_info['integral'] > 3000 && $user_info['integral'] <= 4000){
                    $lists['register_grade'] = 4;
                }
                $lists['register'] = $base['bus_register'];
                $lists['login'] = $base['bus_login'];
                $lists['sign_in'] = $base['bus_sign_in'];
                $lists['recharge'] = $base['bus_recharge'];
                $lists['commission'] = $base['bus_commission'];
                $lists['register_state'] = 1;
                $lists['login_state'] = 0;
                $lists['sign_in_state'] = 0;
                $lists['recharge_state'] = 0;
                $lists['commission_state'] = 0;
                if (trim(@date('Y-m-d', strtotime($user_info['login_at']))) == trim(date('Y-m-d'))){
                    $lists['login_state'] = 1;
                }
                if (trim(@date('Y-m-d', strtotime($user_info['sign_in_at']))) == trim(date('Y-m-d'))){
                    $lists['sign_in_state'] = 1;
                }
                if (trim(@date('Y-m-d', strtotime($recharge))) == trim(date('Y-m-d'))){
                    $lists['recharge_state'] = 1;
                }
                if (trim(@date('Y-m-d', strtotime($profit))) == trim(date('Y-m-d'))){
                    $lists['commission_state'] = 1;
                }
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户提现
     * @route api.user.userCashOut
     * @param user_id 用户id
     * @param amount 提现金额
     * @param bank_no 银行账户
     * @param bank_user 开户行姓名
     * @param phone 提现人手机号
     * @param bank_name 开户行
     */
    public function userCashOut(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['id','username','balance','profit','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($user_info['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($user_info['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($user_info['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }


            $amount = $request->post("amount");
            $bank_no = (string)$request->post("bank_no");
            $bank_name = (string)$request->post("bank_name");
            $phone = (string)$request->post("phone");
            $bank_user = (string)$request->post("bank_user");
            if (empty($phone) || empty($amount) || empty($bank_name) || empty($bank_no) || empty($bank_user)){
                return response()->json(["code"=>0, "msg"=>'参数错误']);
            }
            if(!preg_match('/^((13|14|15|16|17|18|19)[0-9]\d{8})$/', $phone)){
                return response()->json(["code"=>0, "msg"=>'请填写正确的手机号码']);
            }
            //验证金额是否足够
            if ($amount < 100) {
                return response()->json(["code"=>0, "msg"=>'提现金额不能低于100']);
            }
            if($user_info['type'] == 1){
                if (floatval($user_info['balance']) < $amount) {
                    return response()->json(["code"=>0, "msg"=>'余额不足']);
                }
            }else {
                if (floatval($user_info['profit']) - floatval($user_info['cash']) < $amount) {
                    return response()->json(["code"=>0, "msg"=>'可提现金额不足']);
                }
            }

            $data = [];
            $data['pay_sn'] = Buys::makePaySn($user_id);
            $data['user_id'] = $user_id;
            $data['user_name'] = $user_info['username'];
            $data['phone'] = $phone;
            $data['amount'] = $amount;
            $data['bank_name'] = $bank_name;
            $data['bank_no'] = $bank_no;
            $data['bank_user'] = $bank_user;
            $insert = CashOuts::create($data);
            if (!$insert) {
                return response()->json(["code"=>0, "msg"=>'提现失败']);
            }

            if($user_info['type'] == 1){
                Users::where('id',$user_id)->decrement('balance',$amount);
            }else {
                Users::where('id',$user_id)->decrement('profit',$amount);
                Users::where('id',$user_id)->increment('cash',$amount);
            }
            //生成未处理数据给后台
            $maps = [
                'title' => '未处理提现：'.$user_info['username'],
                'type' => 8,
            ];
            AdminAgencys::create($maps);
            return response()->json(["code"=>1, "msg"=>'提现成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户提现记录列表
     * @route api.user.userCashOutLogs
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     */
    public function userCashOutLogs(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);

            $params['user_id'] = $user_id;
            $params['status'] = 2;
            $lists = CashOuts::select(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date ,GROUP_CONCAT(id) as ids"))
                ->where(function ($query) use ($params) {
                    if(isset($params['user_id']) && $params['user_id']) {
                        $query ->where('user_id',$params['user_id']);
                    }
                    if(isset($params['status']) && $params['status']) {
                        $query ->where('status',$params['status']);
                    }
                })->where('status','<>',-1)
                ->groupBy(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))
                ->orderBy("date","desc")->paginate($limit, null, null, $page);

            foreach ($lists as $key=>$val){
                $ids = explode(",", $val['ids']);
                $lists[$key]['list'] = CashOuts::allLists(['id'=>$ids], ['id','user_id','amount','status']);
                unset($val['ids']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户站内消息列表
     * @route api.user.userMailsLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     * @param status 类型 1:未读 2:已读
     */
    public function userMailsLists(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);
            $status = (int)$request->post('status');//类型 1:未读 2:已读

            $params['user_id'] = $user_id;
            $params['status'] = $status;
            $lists = Mails::select(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date ,GROUP_CONCAT(id) as ids"))
                ->where(function ($query) use ($params) {
                    if(isset($params['user_id']) && $params['user_id']) {
                        $query ->where('user_id',$params['user_id']);
                    }
                    if(isset($params['status']) && $params['status']) {
                        $query ->where('status',$params['status']);
                    }
                })->where('status','<>',-1)
                ->groupBy(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))
                ->orderBy("date","desc")->paginate($limit, null, null, $page);
            foreach ($lists as $key=>$val){
                $ids = explode(",", $val['ids']);
                $lists[$key]['list'] = Mails::allLists(['id'=>$ids], ['id','title','user_id','status']);
                unset($val['ids']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户站内消息详情
     * @route api.user.userMailsDetails
     * @param user_id 用户id
     * @param maile_id 消息id
     */
    public function userMailsDetails(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }


            $maile_id = (int)$request->post('maile_id');//消息id
            if (empty($maile_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $lists = Mails::details(['id'=>$maile_id,'user_id'=>$user_id], $fields=['*']);
            Mails::where('id',$maile_id)->update(['status'=>2]);//变为已读

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户站内消息标记为已读
     * @route api.user.userMailsRead
     * @param user_id 用户id
     * @param maile_id 消息id(字符串：逗号隔开)
     */
    public function userMailsRead(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($users['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($users['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($users['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $maile_id = $request->post('maile_id');//消息id
            if (empty($maile_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $ids = explode(',',$maile_id);

            Mails::where('user_id',$user_id)->whereIn('id',$ids)->update(['status'=>2]);//变为已读

            return response()->json(["code"=>1, "msg"=>'操作成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户站内消息删除
     * @route api.user.userMailsDelete
     * @param user_id 用户id
     * @param maile_id 消息id(字符串：逗号隔开)
     */
    public function userMailsDelete(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($users['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($users['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($users['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $maile_id = $request->post('maile_id');//消息id
            if (empty($maile_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $ids = explode(',',$maile_id);

            Mails::where('user_id',$user_id)->whereIn('id',$ids)->update(['status'=>-1]);//软删除

            return response()->json(["code"=>1, "msg"=>'删除成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户投诉建议列表
     * @route api.user.userFeedbacksLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     * @param isreply 类型 1:未读 2:已读
     */
    public function userFeedbacksLists(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);
            $isreply = (int)$request->post('isreply');//类型 1:未读 2:已读

            $params['user_id'] = $user_id;
            $params['isreply'] = $isreply;
            $lists = Feedbacks::select(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date ,GROUP_CONCAT(id) as ids"))
                ->where(function ($query) use ($params) {
                    if(isset($params['user_id']) && $params['user_id']) {
                        $query ->where('user_id',$params['user_id']);
                    }
                    if(isset($params['isreply']) && $params['isreply']) {
                        $query ->where('isreply',$params['isreply']);
                    }
                })->where('status','<>',-1)
                ->groupBy(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))
                ->orderBy("date","desc")->paginate($limit, null, null, $page);
            foreach ($lists as $key=>$val){
                $ids = explode(",", $val['ids']);
                $lists[$key]['list'] = Feedbacks::allLists(['id'=>$ids], ['id','content','user_id','isreply']);
                unset($val['ids']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户投诉建议详情
     * @route api.user.userFeedbacksDetails
     * @param user_id 用户id
     * @param feed_id 建议id
     */
    public function userFeedbacksDetails(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $feed_id = (int)$request->post('feed_id');//建议id
            if (empty($feed_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $lists = Feedbacks::details(['id'=>$feed_id,'user_id'=>$user_id], $fields=['*']);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户投诉建议添加
     * @route api.user.userFeedbacksAdd
     * @param user_id 用户id
     * @param content 内容
     * @param images 图片
     */
    public function userFeedbacksAdd(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($users['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($users['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($users['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $images = (string)$request->post('images');
            if (!empty($images)){
                $images = explode(',',$images);
            }

            $params = [
                'user_id' => $user_id,
                'user_name' => $users['username'],
                'content' => (string)$request->post('content'),
                'images' => $images,
                'created_at' => date('Y-m-d H:i:s'),
            ];
            Feedbacks::create($params);

            return response()->json(["code"=>1, "msg"=>'添加成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户投诉建议删除
     * @route api.user.userFeedbacksDelete
     * @param user_id 用户id
     * @param feed_id 建议id(字符串：逗号隔开)
     */
    public function userFeedbacksDelete(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($users['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($users['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($users['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $feed_id = $request->post('feed_id');//建议id
            if (empty($feed_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $ids = explode(',',$feed_id);

            Feedbacks::where('user_id',$user_id)->whereIn('id',$ids)->update(['status'=>-1]);//删除

            return response()->json(["code"=>1, "msg"=>'删除成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户修改密码
     * @route api.user.userChangePwd
     * @param user_id 用户id
     * @param mobile 手机号
     * @param password 新密码
     * @param confirmc_pwd 确认密码
     * @param code 短信验证码
     */
    public function userChangePwd (Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($users['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($users['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($users['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $mobile = (string)$request->post('mobile');
            $password = (string)$request->post('password');
            $confirmc_pwd = (string)$request->post('confirmc_pwd');
            $code = (string)$request->post('code');
            if(empty($mobile) || empty($password) || empty($confirmc_pwd) || empty($code)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            if(!preg_match('/^((13|14|15|16|17|18|19)[0-9]\d{8})$/', $mobile)) return response()->json(["code"=>0, "msg"=>'请填写正确的手机号码']);
            if($password !== $confirmc_pwd){
                return response()->json(["code"=>0, "msg"=>'两次密码输入不一致,请重新输入']);
            }

            $info = Users::where(['id'=>$user_id,'mobile'=>$mobile])->where('status','<>',-1)->first();
            if(!empty($info)){
                //检查验证码是否正确
                $cache = cache()->get('sms-'.$mobile);
                if(empty($cache)) return response()->json(["code"=>0, "msg"=>'短信验证码已过期']);//过期
                if($cache['code'] != $code) return response()->json(["code"=>0, "msg"=>'短信验证码输入错误']);
                cache()->delete('sms-'.$mobile);//删除验证码

                $info->mobile = $mobile;
                $info->password = bcrypt($password);
                $info->save();
                return response()->json(["code"=>1, "msg"=>'修改成功,请重新登录']);
            }else{
                return response()->json(["code"=>0, "msg"=>'该用户不存在']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户修改手机号
     * @route api.user.userChangeMobile
     * @param user_id 用户id
     * @param old_mobile 原手机号
     * @param new_mobile 新手机号
     * @param code 短信验证码
     */
    public function userChangeMobile(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($users['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($users['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($users['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $old_mobile = (string)$request->post('old_mobile');
            $new_mobile = (string)$request->post('new_mobile');
            $code = (string)$request->post('code');
            if(empty($old_mobile) || empty($new_mobile) || empty($code)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $str = '/^((13|14|15|16|17|18|19)[0-9]\d{8})$/';
            if(!preg_match($str, $old_mobile) || !preg_match($str, $new_mobile)){
                return response()->json(["code"=>0, "msg"=>'请填写正确的手机号码']);
            }
            if($old_mobile == $new_mobile){
                return response()->json(["code"=>0, "msg"=>'新手机号和原手机号相同，无需修改']);
            }
            $info = Users::where(['id'=>$user_id,'mobile'=>$old_mobile])->where('status','<>',-1)->first();
            if(!empty($info)){
                //检查验证码是否正确
                $cache = cache()->get('sms-'.$new_mobile);
                if(empty($cache)) return response()->json(["code"=>0, "msg"=>'短信验证码已过期']);//过期
                if($cache['code'] != $code) return response()->json(["code"=>0, "msg"=>'短信验证码输入错误']);
                cache()->delete('sms-'.$new_mobile);//删除验证码

                $info->mobile = $new_mobile;
                $info->save();
                return response()->json(["code"=>1, "msg"=>'修改成功,请重新登录']);
            }else{
                return response()->json(["code"=>0, "msg"=>'该用户不存在']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户需求列表
     * @route api.user.userDemandLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     * @param state 状态 1:招标中 2:已完成 不传或其他：全部
     */
    public function userDemandLists(Request $request){
        try {
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);
            $state = (int)$request->post('state');//状态 1:招标中 2:已完成 3:审核中 不传或其他：全部
            if($state == 1){
                $params['status'] = 1;
                $params['bid'] = 2;
            }elseif ($state == 2){
                $params['status'] = 1;
                $params['bid'] = 3;
            }elseif ($state == 3){
                $params['status'] = 2;
            }
            if($users['type'] == 1){//HR
                $params['user_id'] = $user_id;
                $fields = ['id','user_id','title','price','content','limit_num','number','end_at','created_at','urgent','status','bid'];
                $lists = Demands::centerList($params, $fields, $page, $limit);
                foreach ($lists as $key => $val){
                    if ($val['number'] == $val['limit_num'] || trim(@date('Y-m-d', strtotime($val['end_at']))) < date('Y-m-d')){
                        $end_state = 1;//已过截止日期或者投标人数已满，不能再投标
                    }else{
                        $end_state = 0;//可以投标
                    }
                    //需求状态判断
                    if($val['status'] == 1){
                        if ($val['bid'] == 2 && $end_state == 0){
                            $lists[$key]['state'] = 1;//投标中
                        }elseif ($val['bid'] == 3 || $val['bid'] == 4 || $end_state == 1){
                            $lists[$key]['state'] = 2;//已中标或已完成
                        }elseif ($val['bid'] == 1){
                            $lists[$key]['state'] = 3;//审核中
                        }
                    }elseif ($val['status'] == 2){
                        $lists[$key]['state'] = 3;//审核中
                    }elseif ($val['status'] == 3){
                        $lists[$key]['state'] = 4;//审核失败
                    }elseif ($val['status'] == 4){
                        $lists[$key]['state'] = 5;//已锁定
                    }
                    $lists[$key]['end_at'] = trim(@date('m-d', strtotime($val['end_at'])));
                    $lists[$key]['start_at'] = trim(@date('m-d', strtotime($val['created_at'])));
                    $lists[$key]['price'] = floatval($val['price']);
                    $lists[$key]['bid_list'] = BidLists::allLists(['demand_id'=>$val['id'],'user_id'=>$user_id], ['id','demand_id','user_id','store_id','store_name']);
                }
            }elseif ($users['type'] == 2){
                $demand_id = [];
                $info = BidLists::where('store_id',$user_id)->get(['id','demand_id','user_id','store_id','store_name'])->toArray();
                if (empty($info)){
                    $lists = new LengthAwarePaginator(
                        array_slice([], ($page * 10) - 10, 10, false),
                        count([]),
                        10, $page,
                        ['path' => $request->url(), 'query' => $request->query()]
                    );
                }else {
                    foreach ($info as $key => $val){
                        array_push($demand_id, $val['demand_id']);
                    }
                    $params['id'] = $demand_id;
                    $fields = ['id','user_id','title','price','content','limit_num','number','end_at','created_at','urgent','status','bid'];
                    $lists = Demands::allLists($params, $fields, $page, $limit,'created_at');
                    foreach ($lists as $key => $val){
                        if ($val['number'] == $val['limit_num'] || trim(@date('Y-m-d', strtotime($val['end_at']))) < date('Y-m-d')){
                            $end_state = 1;//已过截止日期或者投标人数已满，不能再投标
                        }else{
                            $end_state = 0;//可以投标
                        }
                        //需求状态判断
                        if($val['status'] == 1){
                            if ($val['bid'] == 2 && $end_state == 0){
                                $lists[$key]['state'] = 1;//投标中
                            }elseif ($val['bid'] == 3 || $val['bid'] == 4 || $end_state == 1){
                                $lists[$key]['state'] = 2;//已中标或已完成
                            }
                        }elseif ($val['status'] == 4){
                            $lists[$key]['state'] = 5;//已锁定
                        }
                        $lists[$key]['end_at'] = trim(@date('m-d', strtotime($val['end_at'])));
                        $lists[$key]['start_at'] = trim(@date('m-d', strtotime($val['created_at'])));
                        $lists[$key]['price'] = floatval($val['price']);
                    }
                }
            }
            return response()->json([
                "code" => 1,
                "msg" => "操作成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户活动列表
     * @route api.user.userActLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     * @param type 类型 1:报名中 2:已举办 不传或其他:全部
     */
    public function userActLists(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);

            $type = (int)$request->post('type');//类型 1:报名中 2:已举办 不传或其他:全部

            $now_time = date('Y-m-d H:i:s');
            $params = [];
            if($type == 1){
                $params['sign_at'] = $now_time;
            }elseif ($type == 2){
                $params['start_at'] = $now_time;
            }

            if($users['type'] == 2){
                $params['user_id'] = $user_id;
                $fields = ['id','thumb','title','start_at','view','cost','number','enroll_at','start_at','cate_pid','cate_id','status'];
                $lists = Activitys::allLists($params,$fields,$page,$limit,'start_at');
                foreach ($lists as $k=>$v){
                    if($v['status'] == 1){
                        if($now_time <= $v['start_at']){
                            $lists[$k]['act_state'] = '报名中';//报名中
                        }else {
                            $lists[$k]['act_state'] = '已举办';//已举办
                        }
                    }elseif ($v['status'] == 4) {
                        $lists[$k]['act_state'] = '已取消';//已取消
                    }else{
                        $lists[$k]['act_state'] = '审核中';//审核中
                    }
                }
            }elseif ($users['type'] == 1){
                $activity_id = [];
                $info = SignUps::where('user_id',$user_id)->where('status','<>',-1)->get(['id','activity_id','user_id'])->toArray();
                if (empty($info)){
                    $lists = new LengthAwarePaginator(
                        array_slice([], ($page * 10) - 10, 10, false),
                        count([]),
                        10, $page,
                        ['path' => $request->url(), 'query' => $request->query()]
                    );
                }else {
                    foreach ($info as $key => $val){
                        array_push($activity_id, $val['activity_id']);
                    }
                    $params['id'] = $activity_id;
                    $fields = ['id','thumb','title','start_at','view','cost','number','enroll_at','start_at','cate_pid','cate_id','status'];
                    $lists = Activitys::allLists($params,$fields,$page,$limit,'start_at');
                    foreach ($lists as $k=>$v){
                        if($v['status'] == 1){
                            if($now_time <= $v['start_at']){
                                $lists[$k]['act_state'] = '报名中';//报名中
                            }else {
                                $lists[$k]['act_state'] = '已举办';//已举办
                            }
                        }elseif ($v['status'] == 4) {
                            $lists[$k]['act_state'] = '已取消';//已取消
                        }else{
                            $lists[$k]['act_state'] = '审核中';//审核中
                        }
                    }
                }
            }


            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }


    /**
     * HR订单列表
     * @route api.user.hrOrderLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     * @param state_type 类型：1待付款 2待发货 3待收货 4待评价 不传或其他值：全部
     */
    public function hrOrderLists(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',5);//条数
            $state_type = (int)$request->post("state_type");
            $params = [];
            $params['user_id'] = $user_id;
            $params['status'] = -1;
            if ($state_type == 1){
                $params['order_state'] = 2;
            }elseif ($state_type == 2){
                $params['order_state'] = 3;
            }elseif ($state_type == 3){
                $params['order_state'] = 4;
            }elseif ($state_type == 4){
                $params['order_state'] = 5;
                $params['evaluation_state'] = 1;
                $params['refund_state'] = 0;
            }
            $fields = ['id','order_sn','pay_sn','store_id','store_name','created_at','order_amount','pay_price','order_state','evaluation_state'];
            $order_list = Orders::allLists($params,$fields,$page,$limit,'id','desc',['order_goods']);

            foreach ($order_list as $key => $order) {
                //默认该订单的不可操作性
                $order['is_cancel'] = 0;//取消订单
                $order['is_pay'] = 0;//付款
                $order['is_take'] = 0;//收货
                $order['is_evaluation'] = 0;//评价
                $order['is_delete'] = 0;//删除
                //显示取消订单
                if($order['order_state'] == 2){
                    $order['is_cancel'] = 1;
                    $order['is_pay'] = 1;
                }
                if($order['order_state'] == 3){
                    $order['is_cancel'] = 1;
                }
                //显示收货
                if($order['order_state'] == 4){
                    $order['is_take'] = 1;
                }
                //显示评价
                if($order['order_state'] == 5 && $order['evaluation_state'] == 1){
                    $order['is_evaluation'] = 1;
                }
                //显示删除订单
                if($order['order_state'] == 1 || $order['order_state'] == 5){
                    $order['is_delete'] = 1;
                }
                //取商品列表
                $order_list[$key]['goods_list'] =OrderGoods::where('order_id',$order['id'])->get();
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $order_list
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * HR订单详情
     * @route api.user.hrOrderDetails
     * @param user_id 用户id
     * @param order_id 订单号
     */
    public function hrOrderDetails(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $order_id = (int)$request->post("order_id");
            if(empty($order_id) || $order_id <= 0) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $params['id'] = $order_id;
            $params['user_id'] = $user_id;
            $fields = ['id','order_sn','pay_sn','user_id','user_name','store_id','store_name','order_amount','pay_price',
                'order_state','evaluation_state','created_at','pay_time','shipping_time','shipping_code','shipping_sn','reciver_info'];
            $order_info = Orders::getOrderInfo($params,$fields);
            if(empty($order_info)) return response()->json(["code"=>0, "msg"=>'该订单不存在']);

            //默认该订单的不可操作性
            $order_info['is_cancel'] = 0;//取消订单
            $order_info['is_pay'] = 0;//付款
            $order_info['is_logistics'] = 0;//查看物流
            $order_info['is_take'] = 0;//收货
            $order_info['is_evaluation'] = 0;//评价
            $order_info['is_delete'] = 0;//删除
            //显示取消订单
            if($order_info['order_state'] == 2){
                $order_info['is_cancel'] = 1;
                $order_info['is_pay'] = 1;
            }
            if($order_info['order_state'] == 3){
                $order_info['is_cancel'] = 1;
            }
            //显示收货
            if($order_info['order_state'] == 4){
                $order_info['is_logistics'] = 1;
                $order_info['is_take'] = 1;
            }
            //显示评价
            if($order_info['order_state'] == 5 && $order_info['evaluation_state'] == 1){
                $order_info['is_evaluation'] = 1;
            }
            //显示删除订单
            if($order_info['order_state'] == 1 || $order_info['order_state'] == 5){
                $order_info['is_delete'] = 1;
            }
            $order_info['reciver_info'] = unserialize($order_info['reciver_info']);
            $order_info['goods_list'] =OrderGoods::where(['order_id'=>$order_id,'user_id'=>$user_id])->get();

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $order_info
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * HR订单状态操作
     * @route api.user.hrOrderChangeState
     * @param user_id 用户id
     * @param order_id 订单号
     * @param state_type 类型：1:取消订单  2:确认收货  3:删除订单
     */
    public function hrOrderChangeState(Request $request) {
        try {
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($user_info['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($user_info['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($user_info['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $order_id = (int)$request->post("order_id");
            $state_type = (int)$request->post("state_type",1);
            if (empty($order_id) || empty($state_type)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $params['id'] = $order_id;
            $params['user_id'] = $user_id;
            $order_info = Orders::getOrderInfo($params,['*']);
            if(empty($order_info)) return response()->json(["code"=>0, "msg"=>'该订单不存在']);

            if ($state_type == 1) {//取消订单
                if($order_info['order_state'] == 2 || $order_info['order_state'] == 3){
                    Orders::changeOrderStateCancel($order_info);
                } else {
                    return response()->json(["code"=>0, "msg"=>'参数错误']);
                }
            } else if ($state_type == 2) {//确认收货
                if($order_info['order_state'] == 4){
                    //更新订单状态
                    $update_order = ['order_state' => 5, 'finnshed_time'=>date('Y-m-d H:i:s')];
                    Orders::where('id',$order_id)->update($update_order);
                    //HR确认订单，供应商获得收益
                    $member_info = Stores::where('id',$order_info['store_id'])->first(['user_id','seller_name']);
                    Users::where('id',$member_info['user_id'])->increment('profit',$order_info['pay_price']);
                    //收益日志记录
                    $users = Users::where('id',$member_info['user_id'])->first(['id','username']);
                    $order_goods = OrderGoods::where('order_id',$order_id)->pluck('goods_name')->toArray();
                    if (!empty($order_goods)){
                        $tit = '商品名称:'.implode('、',$order_goods);
                    }else{
                        $tit = '购买商品';
                    }
                    $profit = [
                        'user_id' => $users['id'],
                        'user_name' => $users['username'],
                        'profit' => '+'.$order_info['pay_price'],
                        'desc' => $tit,
                        'type' => 1,
                    ];
                    ProfitLogs::create($profit);
                    //TODO 收益日志写入后，需修改供应商可提现收益值
                } else {
                    return response()->json(["code"=>0, "msg"=>'参数错误']);
                }
            } else if ($state_type == 3) {
                if($order_info['order_state'] == 1 || $order_info['order_state'] == 5){
                    //删除订单
                    OrderGoods::where('order_id',$order_id)->update(['status'=>-1]);
                    Orders::where('id',$order_id)->update(['status'=>-1]);
                } else {
                    return response()->json(["code"=>0, "msg"=>'参数错误']);
                }
            } else {
                return response()->json(["code"=>0, "msg"=>'参数错误']);
            }
            return response()->json(["code"=>1, "msg"=>'操作成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * HR评价商品
     * @route api.user.hrGoodsEvaluates
     * @param user_id 用户id
     * @param evaluate_array 评价数组
     */
    public function hrGoodsEvaluates(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['id','username','avatar','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($user_info['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($user_info['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($user_info['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
                if($user_info['type'] != 1) return response()->json(["code"=>0, "msg"=>'HR才可以评价商品']);
            }

            $evaluate_array = json_decode($request->post('evaluate_array'));//评价数组
            if (empty($evaluate_array)) return response()->json(["code"=>0, "msg"=>'参数不正确']);

            foreach ($evaluate_array as $key => $val){
                $val = (array)$this->objectToArray($val);
                //获取订单信息
                $order_info = Orders::getOrderInfo(['id'=>$val['order_id'],'user_id'=>$user_id]);
                //判断订单身份
                if ($order_info['user_id'] != $user_id) return response()->json(["code"=>0, "msg"=>'参数错误']);
                //订单为'已收货'状态，并且未评论
                if($order_info['order_state'] != 5 && $order_info['evaluation_state'] != 1){
                    return response()->json(["code"=>0, "msg"=>'订单信息错误']);
                }

                //获取当前商品的评价图片
                if (!empty($val['images'])){
                    $evaluate_image = explode(',',$val['images']);
                }else{
                    $evaluate_image = [];
                }

                //评分
                $evaluate_type = $val['type'];
                //默认评语
                $evaluate_comment = $val['content'];
                if (empty($evaluate_comment)) {
                    $evaluate_comment = '不错哦';
                }
                $insert = [
                    'user_id' => $user_id,
                    'user_name' => $user_info['username'],
                    'user_avatar' => $user_info['avatar'],
                    'goods_id' => $val['goods_id'],
                    'goods_name' => Goods::where('id',$val['goods_id'])->value('title'),
                    'content' => $evaluate_comment,
                    'images' => $evaluate_image,
                    'type' => $evaluate_type,
                ];
                Log::info($insert);
                if($insert['type'] == 1){
                    $insert['average_star'] = 5;//好评
                }elseif ($insert['type'] == 2){
                    $insert['average_star'] = 3;//中评
                }elseif ($insert['type'] == 3){
                    $insert['average_star'] = 1;//差评
                }
                GoodsEvaluates::create($insert);
                Orders::where(['id'=>$val['order_id'],'user_id'=>$user_id])->update(['evaluation_state'=>2]);
                Goods::where('id',$insert['goods_id'])->increment('praise');//评论量加1
                //计算好评率
                $all = GoodsEvaluates::where(['goods_id'=>$insert['goods_id']])->where('status','<>',-1)->count();
                $goods = GoodsEvaluates::where(['goods_id'=>$insert['goods_id'], 'type'=>1])->where('status','<>',-1)->count();
                $credit = $goods/$all*100;
                //被评价商品星级
                if($credit <= 20){
                    $star = 1;
                }elseif ($credit >20 && $credit <= 40){
                    $star = 2;
                }elseif ($credit >40 && $credit <= 60){
                    $star = 3;
                }elseif ($credit >60 && $credit <= 80){
                    $star = 4;
                }elseif ($credit >80 && $credit <= 100){
                    $star = 5;
                }
                Goods::where('id',$insert['goods_id'])->update(['credit'=>$credit, 'star'=>$star]);
            }
            return response()->json(["code"=>1, "msg"=>'评价成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * HR收货地址列表
     * @route api.user.hrAddressLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     */
    public function hrAddressLists(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',1);
            $lists = Addresses::allLists(['user_id'=>$user_id], ['*'], $page, $limit);

            return response()->json([
                "code" => 1,
                "msg" => "操作成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * HR收货地址详情
     * @route api.user.hrAddressLists
     * @param user_id 用户id
     * @param address_id 收货地址id
     * @return realname 姓名
     * @return phone 电话
     * @return province 省份
     * @return city 城市
     * @return region 区域
     * @return detail 详细地址
     */
    public function hrAddressDetails(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','bond','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $address_id = (int)$request->post("address_id",4);//收货地址id
            if (empty($address_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $lists = Addresses::details(['id'=>$address_id,'user_id'=>$user_id]);

            return response()->json([
                "code" => 1,
                "msg" => "操作成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * HR收货地址新增或编辑
     * @route api.user.hrAddressLists
     * @param user_id 用户id
     * @param realname 收货人
     * @param phone 电话
     * @param province 省份id
     * @param city 城市id
     * @param region 区域id
     * @param detail 详细地址
     */
    public function hrAddressEdit(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','bond','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($user_info['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($user_info['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($user_info['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
                if ($user_info['type'] != 1) return response()->json(["code"=>0, "msg"=>'供应商没有收获地址']);
            }

            $realname = (string)$request->post("realname");
            $phone = (string)$request->post("phone");
            $province = (int)$request->post("province");
            $city = (int)$request->post("city");
            $region = (int)$request->post("region");
            $detail = (string)$request->post("detail");
            if (empty($user_id) || empty($realname) || empty($phone) || empty($detail)){
                return response()->json(["code"=>0, "msg"=>'参数错误']);
            }
            if(!empty($phone) && !preg_match('/^((13|14|15|16|17|18|19)[0-9]\d{8})$/', $phone)){
                return response()->json(["code"=>0, "msg"=>'请填写正确的手机号码']);
            }
            $province_name = Regions::where('id',$province)->value('name');
            $city_name = Regions::where('id',$city)->value('name');
            $region_name = Regions::where('id',$region)->value('name');

            $address = Addresses::where(['user_id' => $user_id])->where('status','<>',-1)->first();
            if(!empty($address)){
                $address->user_id = $user_id;
                $address->realname = $realname;
                $address->phone = $phone;
                $address->province = $province;
                $address->city = $city;
                $address->region = $region;
                $address->area = $province_name . ' ' . $city_name . ' ' .$region_name;
                $address->detail = $detail;
                $address->default = 1;
            }else{
                $address = new Addresses();
                $address->user_id = $user_id;
                $address->realname = $realname;
                $address->phone = $phone;
                $address->province = $province;
                $address->city = $city;
                $address->region = $region;
                $address->area = $province_name . ' ' . $city_name . ' ' .$region_name;
                $address->detail = $detail;
                $address->default = 1;
            }
            $address->save();

            return response()->json(["code"=>1, "msg"=>'操作成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * HR我的收藏列表
     * @route api.user.hrCollectLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     * @param type 类型 1文档，2新闻，3商品，4店铺，5活动 (必传)
     */
    public function hrCollectLists(Request $request){
        try {
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','bond','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);
            $type = (int)$request->post('type');//类型 1文档，2新闻，3商品，4店铺，5活动
            if (empty($type) || empty($page)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $lists = Collections::allLists(['user_id'=>$user_id, 'type'=>$type], ['id','collect_id','type'],$page,$limit);

            foreach ($lists as $key=>$val) {
                if ($val['type'] == 1){
                    $fields = ['id','thumb','title','summary','view','download','format'];
                    $word = Words::details(['id'=>$val['collect_id']], $fields);
                    $word['word_view'] = strlen($word['view'])>=4 ? '999+' : $word['view'];
                    $word['word_download'] = strlen($word['download'])>=4 ? '999+' : $word['download'];
                    $lists[$key]['word'] = $word;
                }elseif ($val['type'] == 2){
                    $fields = ['id','thumb','title','content','view','collect','created_at'];
                    $news = Articles::details(['id'=>$val['collect_id']], $fields);
                    $news['news_content'] = str_limit(strip_tags($news['content']) , 170 , '...' );//str_limit 字符截取 strip_tags 去除HTML标签
                    $news['news_view'] = strlen($news['view'])>=4 ? '999+' : $news['view'];
                    $news['news_collect'] = strlen($news['collect'])>=4 ? '999+' : $news['collect'];
                    $lists[$key]['news'] = $news;
                }elseif ($val['type'] == 3){
                    $fields = ['id','title','thumb','price','description','view','salenum','type','cate_id','cate_pid'];
                    $goods = Goods::details(['id'=>$val['collect_id']], $fields);
                    $goods['goods_salenum'] = strlen($goods['salenum'])>=4 ? '999+' : $goods['salenum'];
                    $lists[$key]['goods'] = $goods;
                }elseif ($val['type'] == 4){
                    $fields = ['id','store_name','logo','call','view','service','credit','cate_id','hot','quality'];
                    $store = Stores::details(['id'=>$val['collect_id']], $fields);
                    $store['store_view'] = strlen($store['view'])>=4 ? '999+' : $store['view'];
                    $store['store_call'] = strlen($store['call'])>=4 ? '999+' : $store['call'];
                    $store['store_service'] = strlen($store['service'])>=4 ? '999+' : $store['service'];

                    //二级分类
                    $pidTree = array();
                    if (!empty($store['cate_id'])){
                        $store['cate_id'] = explode(',',$store['cate_id']);
                        foreach ($store['cate_id'] as $k => $v){
                            $pidTree[] = Categorys::where('id',$v)->first('name');
                        }
                    }else{
                        $pidTree['name'] = [];
                    }

                    $store['cate_name'] = $pidTree;

                    $lists[$key]['store'] = $store;
                }elseif ($val['type'] == 5){
                    $now_time = date('Y-m-d H:i:s');
                    $fields = ['id','thumb','title','cate_pid','cate_id','view','cost','number','enroll_at','start_at'];
                    $act = Activitys::details(['id'=>$val['collect_id']], $fields);
                    $act['act_view'] = strlen($act['view'])>=4 ? '999+' : $act['view'];
                    $act['act_number'] = strlen($act['number'])>=4 ? '999+' : $act['number'];
                    if($now_time <= $act['enroll_at']){
                        $act['act_state'] = '报名中';
                    }elseif ($now_time >= $act['start_at']){
                        $act['act_state'] = '已举办';
                    }else {
                        $act['act_state'] = '报名结束';
                    }
                    $lists[$key]['act'] = $act;
                }
            }

            return response()->json([
                "code" => 1,
                "msg" => "操作成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * HR文档下载记录列表
     * @route api.user.hrWordDownloadLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     */
    public function hrWordDownloadLists(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','bond','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);

            $lists = WordDownloadLogs::select(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date ,GROUP_CONCAT(id) as ids"))
                ->where('user_id',$user_id)->where('status',1)
                ->groupBy(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))
                ->orderBy("date","desc")->paginate($limit, null, null, $page);

            $fields = ['id','thumb','title','summary','view','download','format','cate_id','cate_pid'];
            foreach ($lists as $key=>$val){
                $ids = explode(",", $val['ids']);
                $download = WordDownloadLogs::allLists(['id'=>$ids], ['word_id']);
                $lists[$key]['list'] = Words::allLists(['id'=>$download], $fields,null,10);
                unset($val['ids']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商收益明细记录列表
     * @route api.user.supplierProfitLogs
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     * @param type 1收益明细 不传：交易明细(只能传1或不传)
     */
    public function supplierProfitLogs(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','bond','type','status']);
            if (empty($users)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);
            $type = (int)$request->post('type');

            $params['user_id'] = $user_id;
            $params['type'] = $type;
            $lists = ProfitLogs::select(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date ,GROUP_CONCAT(id) as ids"))
                ->where(function ($query) use ($params) {
                    if(isset($params['user_id']) && $params['user_id']) {
                        $query ->where('user_id',$params['user_id']);
                    }
                    if(isset($params['type']) && $params['type']) {
                        $query ->where('type',$params['type']);
                    }
                })->where('status','<>',-1)
                ->groupBy(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))
                ->orderBy("date","desc")->paginate($limit, null, null, $page);

            foreach ($lists as $key=>$val){
                $ids = explode(",", $val['ids']);
                $lists[$key]['list'] = ProfitLogs::allLists(['id'=>$ids], ['id','user_id','profit','desc','type'])->toArray();
                unset($val['ids']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商申请退货保证金
     * @route api.user.supplierBondReturn
     * @param user_id 用户id
     * @param bond 退还金额
     * @param desc 原因
     * @param link_name 联系人
     * @param link_phone 联系电话
     */
    public function supplierBondReturn(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','bond','type','status']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($user_info['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($user_info['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($user_info['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $data = [];
            $data['user_id'] = $user_id;
            $data['user_name'] = $user_info['username'];
            $data['bond'] = (int)$request->post('bond');
            $data['desc'] = (string)$request->post('desc');
            $data['link_name'] = (string)$request->post('link_name');
            $data['link_phone'] = (string)$request->post('link_phone');
            if (empty($data['bond']) ||empty($data['desc']) ||empty($data['link_name']) ||empty($data['link_phone'])){
                return response()->json(["code"=>0, "msg"=>'参数错误']);
            }
            if(!preg_match('/^((13|14|15|16|17|18|19)[0-9]\d{8})$/', $data['link_phone'])){
                return response()->json(["code"=>0, "msg"=>'请输入正确的电话号码']);
            }
            if($data['bond'] !== $user_info['bond']){
                return response()->json(["code"=>0, "msg"=>'退还金额错误']);
            }
            BondReturnLogs::create($data);
            //生成未处理数据给后台
            $maps = [
                'title' => '未处理退还保证金：'.$user_info['username'],
                'type' => 9,
            ];
            AdminAgencys::create($maps);

            return response()->json(["code"=>1, "msg"=>'申请成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商取消活动
     * @route api.user.supplierActCancel
     * @param user_id 用户id
     * @param act_id 活动id
     */
    public function supplierActCancel(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status','openid']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($user_info['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($user_info['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($user_info['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $act_id = (int)$request->post('act_id');
            if (empty($act_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            Activitys::where(['id'=>$act_id,'user_id'=>$user_id])->update(['status'=>4]);

            return response()->json(["code"=>1, "msg"=>'取消成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商余额充值
     * @route api.user.supplierRecharge
     * @param user_id 用户id
     * @param money 充值金额
     */
    public function supplierRecharge(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['username','type','status','openid']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($user_info['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($user_info['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($user_info['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $money = (float)$request->post('money');//充值金额
            //余额日志记录
            $balance = [
                'user_id' => $user_id,
                'user_name' => $user_info['username'],
                'money' => $money,
                'balance' => '+'.$money,
                'pay_sn' => Buys::makePaySn($user_id),
                'desc' => '余额充值',
                'type' => 3,
                'pay_state' => 1,
            ];
            $balance_info = BalanceLogs::create($balance);

            //根据订单信息，生成支付二维码
            $detail = '余额充值支付订单';
            $notify_url = route('home.payment.balanceNotifyUrl');
            $payment = new PaymentController();
            $ret=$payment->wxPayment($balance_info['pay_sn'], $balance_info['user_id'],$balance_info['money'],'支付订单',$detail,$notify_url,'JSAPI',$user_info['openid']);

            if($ret['code'] == 1){
                return response()->json(["code"=>1, "msg"=>'获取成功', 'data' => $ret]);
            }else{
                return response()->json(["code"=>0, "msg"=>'获取失败', 'data' =>'']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商订单管理列表
     * @route api.user.supplierOrderLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     * @param state_type 类型：1待发货 2已完成 不传或其他值：全部
     */
    public function supplierOrderLists(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['type','status','openid']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',5);//条数
            $state_type = (int)$request->get("state_type");
            $params = [];
            $store_id = Stores::where('user_id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($store_id)) return response()->json(["code"=>0, "msg"=>'您还未开店，请前往个人中心-店铺管理开店']);
            $params['store_id'] = $store_id;
            if ($state_type == 1){
                $params['pay_status'] = 2;
                $params['shipping_status'] = 1;
                $params['order_state'] = 3;
            }elseif ($state_type == 2){
                $params['order_state'] = 5;
            }
            $fields = ['id','order_sn','pay_sn','store_id','store_name','created_at','order_amount','pay_price','pay_status','shipping_status','order_state','evaluation_state','shipping_code','shipping_sn','pay_method'];
            $order_list = Orders::allLists($params,$fields,$page,$limit,'id','desc');

            foreach ($order_list as $key => $order) {
                //默认该订单的不可操作性
                $order['is_send'] = 0;//发货
                //显示发货
                if($order['pay_status'] == 2 && $order['shipping_status'] == 1 && $order['order_state'] == 3){
                    $order['is_send'] = 1;//发货
                }
                //取商品列表
                $order_list[$key]['goods_list'] =OrderGoods::where('order_id',$order['id'])->get()->toArray();
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $order_list
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商订单管理详情
     * @route api.user.supplierOrderDetails
     * @param user_id 用户id
     * @param order_id 订单号
     */
    public function supplierOrderDetails(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['type','status','openid']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }

            $order_id = (int)$request->post("order_id");
            if(empty($order_id) || $order_id <= 0) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $params['id'] = $order_id;
            $store_id = Stores::where('user_id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($store_id)) return response()->json(["code"=>0, "msg"=>'您还未开店，请前往个人中心-店铺管理开店']);
            $params['store_id'] = $store_id;
//            $params['user_id'] = $user_id;
            $fields = ['id','order_sn','pay_sn','user_id','user_name','store_id','store_name','order_amount','pay_price',
                'order_state','pay_status','shipping_status','evaluation_state','created_at','pay_time','shipping_time','shipping_code','shipping_sn','reciver_info'];
            $order_info = Orders::getOrderInfo($params,$fields);
            if(empty($order_info)) return response()->json(["code"=>0, "msg"=>'该订单不存在']);
            //默认该订单的不可操作性
            $order_info['is_send'] = 0;//发货
            //显示发货
            if($order_info['pay_status'] == 2 && $order_info['shipping_status'] == 1 && $order_info['order_state'] == 3){
                $order_info['is_send'] = 1;//发货
            }
            $order_info['goods_list'] =OrderGoods::where(['order_id'=>$order_id,'store_id'=>$store_id])->get();

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $order_info
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商订单管理-发货
     * @route api.user.supplierDelivery
     * @param user_id 用户id
     * @param order_id 订单id
     * @param shipping_sn 物流单号
     * @param shipping_code 物流公司
     */
    public function supplierDelivery(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['type','status','openid']);
            if (empty($user_info)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($user_info['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($user_info['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($user_info['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
            }

            $order_id = (int)$request->post('order_id');
            $shipping_sn = (string)$request->post('shipping_sn');
            $shipping_code= (string)$request->post('shipping_code');

            if(empty($order_id) || $order_id<0){
                return response()->json(["code"=>0, "msg"=>'参数错误']);
            }
            if(empty($shipping_sn)){
                return response()->json(["code"=>0, "msg"=>'发货单号不能为空!']);
            }
            if(empty($shipping_code)){
                return response()->json(["code"=>0, "msg"=>'配送方式不能为空!']);
            }

            $info = Orders::findOrFail($order_id);
            if(empty($info)){
                return response()->json(["code"=>0, "msg"=>'订单不存在!']);
            }
            if($info['pay_status'] == 1){
                return response()->json(["code"=>0, "msg"=>'请先支付订单!']);
            }
            if($info['shipping_status'] == 2 || $info['order_state'] == 4){
                return response()->json(["code"=>0, "msg"=>'订单已发货!']);
            }

            $update_arr = [];
            $update_arr['shipping_status'] = Orders::SHIPPING_STATUS_2;
            $update_arr['shipping_sn'] = $shipping_sn;
            $update_arr['shipping_code'] = $shipping_code;
            $update_arr['shipping_time'] = date("Y-m-d H:i:s");
            $update_arr['order_state'] = Orders::ORDER_STATE_4;
            $info->update($update_arr);
            //发货成功、推送微信消息
            $wechat_user = Users::where('id',$info['user_id'])->first(['id','openid']);
            if (!empty($wechat_user['openid'])){
                $template_id = 'W4QL6YSFRclJrMceHB9vJfLnJb88bjOw9JvNCHmnyzs';
                $url = 'http://wap.hrqidian.com/#/myOrder';
                $data = [
                    'first' => '亲，您的商品已发货，请注意个人中心订单管理追踪查收',
                    'keyword1' => $info['order_sn'],
                    'keyword2' => OrderGoods::where('order_id',$order_id)->value('goods_name'),
                    'keyword3' => $info['pay_price'].'元',
                    'keyword4' => $update_arr['shipping_time'],
                    'remark' => '虚拟商品（如软件、系统等）请联系小启客服为你提供下载地址 HR小启客服',
                ];
                Wechat::wechatSend($wechat_user['openid'], $template_id, $url, $data);
            }
            return response()->json(["code"=>0, "msg"=>'发货成功!']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }


    /**
     * 对象转换数组
     * @param $e StdClass对象实例
     * @return array|void
     */
    public function objectToArray($e)
    {
        $e = (array)$e;
        foreach ($e as $k => $v) {
            if (gettype($v) == 'resource') return;
            if (gettype($v) == 'object' || gettype($v) == 'array')
                $e[$k] = (array)$this->objectToArray($v);
        }
        return $e;
    }

}